package com.nineclock.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.system.dto.SysRegisterDTO;
import com.nineclock.system.dto.SysUserDTO;
import com.nineclock.system.mapper.SysUserMapper;
import com.nineclock.system.pojo.SysUser;
import com.nineclock.system.service.SMSService;
import com.nineclock.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SMSService smsService;
    @Override
    public Long register(SysRegisterDTO sysRegisterDTO) {
        if (sysRegisterDTO == null){
            throw new NcException(ResponseEnum.ERROR);
        }
        //校验验证码
        Boolean verify = smsService.verify(sysRegisterDTO.getMobile(), sysRegisterDTO.getCheckcode(), SMSConstant.SMS_TYPE_REGISTER);
        if (!verify){
            throw new NcException(ResponseEnum.CODE_IMAGE_ERROR);
        }
        SysUser sysUser = new SysUser();
        //密码加密保存
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        sysUser.setPassword(bCryptPasswordEncoder.encode(sysRegisterDTO.getPassword()));
        sysUser.setMobile(sysRegisterDTO.getMobile());
        sysUser.setCreateTime(new Date());
        sysUser.setStatus((short)1);
        sysUserMapper.insert(sysUser);

        //删除redis验证码
//        smsService.deleteSmsCode(sysRegisterDTO.getMobile(),SMSConstant.SMS_TYPE_REGISTER);
        return sysUser.getId();
    }

    @Override
    public SysUserDTO queryUser(String username) {
            if(username == null){
                throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
            }
            LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SysUser::getUsername, username)
                    .or().eq(SysUser::getMobile, username);
            SysUser user = sysUserMapper.selectOne(wrapper);
            if(user != null){
                return BeanHelper.copyProperties(user, SysUserDTO.class);
            }
            return null;

    }
}
